package tr.gov.tubitak.bilgem.esya.certviewer;

import java.util.Iterator;

/**
 * Created by IntelliJ IDEA.
 * User: ramazan.girgin
 * Date: 12/4/11
 * Time: 3:33 PM
 * To change this template use File | Settings | File Templates.
 */
public class EStringUtils {
     public static final String EMPTY = "";

     public static <T> String join(T... elements) {
        return join(elements, null);
    }

     public static String join(Object[] array, char separator) {
        if (array == null) {
            return null;
        }

        return join(array, separator, 0, array.length);
    }

    public static String join(Object[] array, char separator, int startIndex, int endIndex) {
            if (array == null) {
                return null;
            }
            int noOfItems = endIndex - startIndex;
            if (noOfItems <= 0) {
                return EMPTY;
            }

            StringBuilder buf = new StringBuilder(noOfItems * 16);

            for (int i = startIndex; i < endIndex; i++) {
                if (i > startIndex) {
                    buf.append(separator);
                }
                if (array[i] != null) {
                    buf.append(array[i]);
                }
            }
            return buf.toString();
        }


     public static String join(Iterator<?> iterator, String separator) {

        // handle null, zero and one elements before building a buffer
        if (iterator == null) {
            return null;
        }
        if (!iterator.hasNext()) {
            return EMPTY;
        }
        Object first = iterator.next();
        if (!iterator.hasNext()) {
            return first.toString();
        }

        // two or more elements
        StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small
        if (first != null) {
            buf.append(first);
        }

        while (iterator.hasNext()) {
            if (separator != null) {
                buf.append(separator);
            }
            Object obj = iterator.next();
            if (obj != null) {
                buf.append(obj);
            }
        }
        return buf.toString();
    }

}
